{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import datetime, date\n",
    "import pandas as pd\n",
    "from gs_quant.instrument import IRSwap\n",
    "from gs_quant.backtests.triggers import MeanReversionTrigger, MeanReversionTriggerRequirements\n",
    "from gs_quant.backtests.actions import AddTradeAction\n",
    "from gs_quant.backtests.generic_engine import GenericEngine\n",
    "from gs_quant.backtests.strategy import Strategy\n",
    "from gs_quant.backtests.data_sources import GenericDataSource, MissingDataStrategy\n",
    "from gs_quant.risk import Price\n",
    "from gs_quant.common import Currency, PayReceive\n",
    "from gs_quant.data import Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize session\n",
    "from gs_quant.session import GsSession\n",
    "GsSession.use(client_id=None, client_secret=None, scopes=('run_analytics','read_product_data')) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Buy 10y EUR payers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define backtest dates\n",
    "start_date = date(2021, 6, 1)\n",
    "end_date = datetime.today().date()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define instrument for strategy\n",
    "\n",
    "# IR Swap\n",
    "swap = IRSwap(pay_or_receive=PayReceive.Pay, termination_date='10y', notional_currency=Currency.EUR, \n",
    "              notional_amount=1e4, fixed_rate='ATM', name='swap_10y')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Dataset from Marquee Data Catalog: https://marquee.gs.com/s/developer/datasets/SWAPRATES_STANDARD"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get data set for 10y EUR swap rates\n",
    "ds = Dataset('SWAPRATES_STANDARD')\n",
    "data = ds.get_data(start_date, assetId=['MA5WM2QWRVMYKDK0'])\n",
    "data_10y = data.loc[data['tenor'] == '10y']\n",
    "data_10y.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": true
    }
   },
   "outputs": [],
   "source": [
    "# Mean Reversion Trigger\n",
    "\n",
    "# Define our actions: add the swap\n",
    "action = AddTradeAction(swap)\n",
    "\n",
    "# Define data source\n",
    "s = pd.Series(data_10y['rate'].to_dict())\n",
    "data_source = GenericDataSource(s, MissingDataStrategy.fill_forward) \n",
    "\n",
    "# Define bounds\n",
    "z_score_bound = 2\n",
    "rolling_mean_window = 30\n",
    "rolling_std_window = 30\n",
    "\n",
    "# Build trigger requirements\n",
    "# Sell when value hits z_score_bound on up side, Buy when value hits z_score_bound on down side\n",
    "# Close out position when value crosses mean for the rolling_mean_window\n",
    "trig_req = MeanReversionTriggerRequirements(data_source, z_score_bound, rolling_mean_window, rolling_std_window)\n",
    "trigger = MeanReversionTrigger(trig_req, action)\n",
    "strategy = Strategy(None, trigger)\n",
    "\n",
    "# Run backtest daily\n",
    "GE = GenericEngine()\n",
    "backtest = GE.run_backtest(strategy, start=start_date, end=end_date, frequency='1b', show_progress=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View backtest trade ledger\n",
    "backtest.trade_ledger()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View results summary\n",
    "backtest.result_summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View Performance\n",
    "pd.DataFrame({'Generic backtester': backtest.result_summary['Cumulative Cash'] + backtest.result_summary[Price]}).plot(figsize=(10, 6), title='Performance')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}